var app = getApp()
var WxParse = require('../../wxParse/wxParse.js');
var course = require('../more-course/model/CourseModel.js')
var json=require('../../utils/json_helper.js')
var pay=require('../componet/pay/PayMentModel.js')
import SystemInfoUtil from '../../utils/SystemInfoUtil.js'
var bottomAnimation = wx.createAnimation({
  duration: 300,
  timingFunction: 'linear',
  height: 0,
  top: 0,
  bottom: 0,
  right: 0,
  backgroundColor: '#fff',
  opcity: 0.6
})
Page({

  /**
   * 页面的初始数据
   */
  data: {
    _buyCount: 1,
    curentCourseNo: '0',
    bottomViewShow: false,
    animationData: '',
    showDesExpand: false,
    ellipsis: true,
    showPayButtom:false,
    bk:'',//分销导航进来必须有
    courseDetailInfo: {},
    payChannel:[{code:'1012',text:'微信支付'},{code:'1088',text:'粉币支付'}],
    currentShowTeacherName:'',
    isIOS:false//ios bu能显示价格，支付购买等
  },
  coverLoadError: function(event) {
    this.setData({
      ['courseDetailInfo.cover']: '../../images/course-cover-default.jpg'
    });
  },
  headLoadError: function(event) {
    this.setData({
      ['courseDetailInfo.teacherHead']: '../../images/icons/icon_teacher_1.png'

    });
  },
  ellipsis: function() {
    var value = !this.data.ellipsis;
    this.setData({
      ellipsis: value
    })
  },
  turn2TeacherHome: function(event) {
    var teacherId = event.currentTarget.dataset.id
    var _url = '../teacher-home/teacher?id=' + teacherId
    console.log(_url);
    wx.navigateTo({
      url: _url,
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this
    var courseNo = options.courseId
    var mTitle = options.title
    var teacherName = options.teacherName
    this.setData({
      currentShowTeacherName: teacherName
    })
    var _bk = options.bk ? options.bk:''
    wx.setNavigationBarTitle({
      title: mTitle,
    })
    var _isIOS=SystemInfoUtil.platform == SystemInfoUtil.IOS
    this.setData({
      isIOS: _isIOS
    })
    if (courseNo == null || wx.getStorageSync("userToken").length<=0){
        wx.reLaunch({
          url: '../login/login',
          success: function(res) {},
          fail: function(res) {},
          complete: function(res) {},
        })
        return
    }
    this.setData({
      curentCourseNo: courseNo,
      bk:_bk
    })
    this.loadCourseDetail(courseNo)
  },
  loadCourseDetail(courseNo){
    var that=this
    course.getDetail(courseNo, function (data) {
      var des = data.title + data.remarks + ""
      if (des.length >= 60) {
        that.setData({
          showDesExpand: true
        })
      }
      that.setData({
        courseDetailInfo: data,
        showPayButtom: Number(data.buyFlag)==1?false:true
      })
      if (that.data.currentShowTeacherName.length<=0){
        that.setData({
          currentShowTeacherName: courseDetailInfo.teacherName
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },
  onVideoItemClick: function(event) {
    var videoNo = event.detail.videoNo
    var position = event.detail.position
    var title = event.detail.title
    var _url = '../video-info/video?videoId=' + videoNo;
    _url += '&title=' + title;
    _url += '&courseId=' + this.data.curentCourseNo;
    _url += '&courseFree=' + (this.data.courseDetailInfo.price > 0 ? '1' : '0');
    _url += '&courseBuyFlag=' + (this.data.courseDetailInfo.buyFlag > 0 ? '1' : '0');
    wx.navigateTo({
      url: _url
    })
  },
  imageclick: function(event) {
    console.log('imageclick')
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {
    var shareObject = {
      title: this.data.courseDetailInfo.title + "【"+this.data.courseDetailInfo.remarks+"】",
      path: 'pages/courseinfo/detail?courseId=' + this.data.curentCourseNo + "&title=" + this.data.courseDetailInfo.title,
      imageUrl: this.data.courseDetailInfo.cover,
      success: function(res) {
        wx.showToast({
          title: '分享成功',
          icon: ''
        })
      }
    }
    return shareObject;
  },
  /**
   * 添加购物车
   */
  goShare: function(event) {
    // _openBottomAnimation(this)
    wx.showToast({
      title: '请稍等...',
      icon:''
    })
  },
  /**
   * 立即购买
   */
  buyNow: function(event) {
    var that=this
    wx.showActionSheet({
      itemList: ['微信支付','粉币支付'],
      success: function (res) {
        var bk=that.data.bk
        if (res.tapIndex==0){
          pay.getOrder("1012", "1003", that.data.curentCourseNo, "3002",bk,function(success){
            var data = success.responseData
            pay.pay(data.timeStamp, data.nonceStr, data.package, data.sign, function (state, res) {
              if (state == 0) {
                console.log("支付成功")
                that.buySuccess()
              } else {
                console.log("支付失败")
                that.buyFail()
              }
            })
          })
        } else if (res.tapIndex==1){
          pay.getOrder("1088", "1003", that.data.curentCourseNo, "3002", bk,function (success) {
              //success
            that.buySuccess()
          })
        }
      },
    })
  },
  buySuccess(){
    wx.showToast({
      title: '购买成功',
      icon:'none',
      duration:3000
    })
    this.loadCourseDetail(this.data.curentCourseNo)
  },
  buyFail(){
    wx.showToast({
      title: '支付失败',
      icon: 'none',
      duration: 3000
    })
  },
  /**
   * 选择规格
   */
  selectedSpecifications: function(event) {
    console.log('selectedSpecifications')
    _openBottomAnimation(this)
  },
  closeAnimation: function(event) {
    _closeBottomAnimation(this)
  },
  /**
   * 减少购买个数
   */
  clickByCountReduce: function(event) {
    var currentValue = this.data._buyCount
    if (currentValue > 1) {
      currentValue--
    } else {
      currentValue = 1
    }
    this.setData({
      _buyCount: currentValue
    })
  },
  /**
   * 增加购买个数
   */
  clickByCountAdd: function(event) {
    var currentValue = this.data._buyCount
    var max = this.data.shopDetail.stock
    if (currentValue < max) {
      currentValue++
    } else {
      wx.showToast({
        title: '最多只能购买' + max + '件',
        icon: 'none'
      })
    }
    this.setData({
      _buyCount: currentValue
    })
  },
  /**
   * 确认添加购物车
   */
  specificationsOk: function(event) {
    var shopId = event.currentTarget.dataset.shopid
    wx.showToast({
      title: '添加购物车成功，商品id=' + shopId,
      icon: 'none'
    })
    _closeBottomAnimation(this)
  }
})

function _openBottomAnimation(context) {
  var animation = bottomAnimation
  context.animation = animation
  animation.translateY(-90 + 'vh').step()
  context.setData({
    animationData: animation.export(),
    bottomViewShow: true,
  })
}

function _closeBottomAnimation(context) {
  var animation = bottomAnimation
  context.animation = animation
  animation.translateY(90 + 'vh').step()
  context.setData({
    animationData: animation.export(),
    bottomViewShow: false,
  })
}